package com.young.android.dbreposit;

import java.io.File;
import java.util.ArrayList;

import com.young.android.R;
import com.young.android.common.PubFunction;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SqliteHelper {

    private static String TAG = "SqlliteHelper";
    private static SQLiteDatabase cfgdb = null;
    private static SQLiteDatabase db = null;
    public static Context mContext;

    // RSS数据库
    private final static String DB_NAME = "RSS.db";
    private final static String mCfgDat = "config.db";

    // 模板库
    private final static String mDBDat = "dat/RSS.db";

    public static void setContext(Context context) {
        mContext = context;
    }
    
    /**打开配置库
     * @return
     */
    public static int OpenCfgDB()
    {
      int ireturn = 0;
      File Afile = mContext.getDatabasePath(mCfgDat);
      if (!Afile.exists())
      {
        //不存在创建数据库
        ireturn = CreateCfgDB();
      } else
      {
        // 打开
        cfgdb = mContext.openOrCreateDatabase(mCfgDat, Context.MODE_PRIVATE,
            null);
      }
      return ireturn;
    }
    
    /**创建配置库
     * @return
     */
    private static int CreateCfgDB()
    {
      // 创建库
      cfgdb = mContext.openOrCreateDatabase(mCfgDat, Context.MODE_PRIVATE,
          null);
      StringBuffer sb = new StringBuffer();
      sb.append("create table USERINFO                ");
      sb.append("(                                    ");
      sb.append("   _id               INTEGER,        ");
      sb.append("   GET_REC_COUNT     INTEGER,        ");
      sb.append("   primary key (_id)                 ");
      sb.append("); ");
      return CfgExecSQL(sb.toString());
    }
    
    /**执行查询
     * @param sqlcmd
     * @return
     */
    public static Cursor CfgQuerySql(String sqlcmd)
    {
      Cursor creturn = null;
      try
      {
        creturn = cfgdb.rawQuery(sqlcmd, null);
      } catch (SQLException e)
      {
        // TODO: handle exception
        Log.v(TAG, e.getMessage() + " sqlcmd=" + sqlcmd);
      }
      return creturn;
    }

    /**执行语句
     * @param sqlcmd
     * @return
     */
    public static int CfgExecSQL(String sqlcmd)
    {
      int ireturn = 0;
      try
      {
        cfgdb.execSQL(sqlcmd);
      } catch (SQLException e)
      {
        // TODO: handle exception
        Log.v(TAG, e.getMessage() + " sqlcmd=" + sqlcmd);
        ireturn = R.string.exec_sql_error;
      }
      return ireturn;
    }

    /**
     * 开始事务
     */
    public static void CfgbeginTransaction()
    {
      if (!cfgdb.inTransaction())
      {
        cfgdb.beginTransaction();
      }
    }

    /**
     * 结束事务
     */
    public static void CfgendTransaction(boolean bRollback)
    {
      if (cfgdb.inTransaction())
      {
        // 不需要回滚的就提交
        if (!bRollback)
        {
          cfgdb.setTransactionSuccessful();
        }
        cfgdb.endTransaction();
      }
    }  

    /**
     * 打开数据库
     * 
     * @return 打开状态，创建或已存在直接打开
     */
    public static int openRSSDB() {
        int ireturn = 0;
        File Afile = mContext.getDatabasePath(DB_NAME);
        // 判断是否存在
        if (!Afile.exists()) {
            Log.i(TAG, "create");
            ireturn = createBusinessDB();
        }
        // 打开数据库
        if (ireturn == 0) {
            db = mContext.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        }
        return ireturn;
    }

    /**
     * 创建数据库
     * 
     * @return
     */
    public static int createBusinessDB() {
        int ireturn = R.string.create_db_error;
        File Afile = mContext.getDatabasePath(DB_NAME);
        // 不存在才复制模板
        if (!Afile.exists()) {
            if (PubFunction.SaveAssetsToFile(mDBDat, Afile))
                ireturn = 0;
        }
        return ireturn;
    }

    /**
     * 执行查询
     * 
     * @param sqlcmd
     * @return
     */
    public static Cursor QuerySql(String sqlcmd) {
        Cursor creturn = null;
        try {
            creturn = db.rawQuery(sqlcmd, null);
        } catch (Exception e) {
            // TODO: handle exception
            Log.v(TAG, e.getMessage() + " sqlcmd=" + sqlcmd);
            e.printStackTrace();
        }
        return creturn;
    }

    /**
     * 执行语句
     * 
     * @param sqlcmd
     * @return
     */
    public static int ExecSQL(String sqlcmd) {
        int ireturn = R.string.exec_sql_error;
        try {
            db.execSQL(sqlcmd);
            ireturn = 0;
        } catch (SQLException e) {
            // TODO: handle exception
            Log.v(TAG, e.getMessage() + " sqlcmd=" + sqlcmd);
            e.printStackTrace();
        }
        return ireturn;
    }

    public static int ExecSQLList(ArrayList<String> sqlList) {
        int ireturn = R.string.exec_sql_error;
        try {
            int isize = sqlList.size();
            for (int i = 0; i < isize; i++) {
                db.execSQL(sqlList.get(i));
            }
            ireturn = 0;
        } catch (SQLException e) {
            // TODO: handle exception
            Log.v(TAG, e.getMessage());
            e.printStackTrace();
        }
        return ireturn;
    }

    /**
     * 开始事务
     */
    public static void beginTransaction() {
        if (!db.inTransaction()) {
            db.beginTransaction();
        }
    }

    /**
     * 结束事务
     */
    public static void endTransaction(int ireturn) {
        if (db.inTransaction()) {
            if (ireturn == 0) {
                db.setTransactionSuccessful();
            }
            db.endTransaction();
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        if (db != null) {
            db.close();
        }
        if (cfgdb != null) {
            db.close();
        }
    }

}
